package com.cblz.bd.common.core.utils;

import com.cblz.bd.common.core.entity.system.Tree;

import java.util.ArrayList;
import java.util.List;

/**
 * {@code @Name:} TreeUtil
 * {@code @Description: } 构建树形结构的数据，菜单-路由等
 * {@code @Author:} by yanjieping
 * {@code @CreateDate:} 2022/11/10 - 周四
 */
public class TreeUtil<T> {

    private static final String TOP_NODE_ID = "0";

    /**
     * 用于构建菜单或部门树
     *
     * @param nodes nodes
     * @return <T> List<? extends Tree>
     */
    public static <T> java.util.List<? extends Tree<?>> build(java.util.List<? extends Tree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        List<Tree<T>> topNodes = new ArrayList<>();
        nodes.forEach(node -> {
            String pid = String.valueOf(node.getPid());
            if (pid == null || TOP_NODE_ID.equals(pid)) {
                topNodes.add(node);
                return;
            }
            for (Tree<T> n : nodes) {
                String id = String.valueOf(n.getId());
                if (id != null && id.equals(pid)) {
                    if (n.getChildren() == null) {
                        n.initChildren();
                    }
                    n.getChildren().add(node);
                    return;
                }
            }
            if (topNodes.isEmpty()) {
                topNodes.add(node);
            }
        });
        return topNodes;
    }

    /**
     * 树形结构转换成集合List
     *
     * @param tree       树形结构数据
     * @param targetList 返回集合
     * @param <T>        实体类
     * @param <R>        实体类的子类-树形结构类
     */
    public static <T, R> void recursionTreeToList(List<? extends Tree<T>> tree, List<R> targetList) {
        if (!tree.isEmpty()) {
            for (Tree<T> tTree : tree) {
                targetList.add((R) tTree);
                List<Tree<T>> children = tTree.getChildren();
                if (children != null && !children.isEmpty()) {
                    recursionTreeToList(children, targetList);
                }
            }
        }
    }
}
